package com.example.iot.mapper.mysql.handlers;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.example.iot.util.UUIDUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

/**
 * @author ChenXiangpeng
 */
@MappedTypes(UUID.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class UUIDTypeHandler extends BaseTypeHandler<UUID> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, UUID uuid, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, uuid.toString().replace(StringPool.DASH, StringPool.EMPTY));
    }

    @Override
    public UUID getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String uuid = resultSet.getString(s);
        try{
            return UUIDUtil.fromString(uuid);
        }catch (IllegalArgumentException | NullPointerException e){
            return null;
        }
    }

    @Override
    public UUID getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String uuid = resultSet.getString(i);
        try{
            return UUIDUtil.fromString(uuid);
        }catch (IllegalArgumentException | NullPointerException e){
            return null;
        }
    }

    @Override
    public UUID getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String uuid = callableStatement.getString(i);
        try{
            return UUIDUtil.fromString(uuid);
        }catch (IllegalArgumentException | NullPointerException e){
            return null;
        }
    }
}
